from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError


async def http_exception_handler( req: Request, exec: HTTPException):
    return JSONResponse({
        "code": exec.status_code,
        "msg": exec.detail,
        "data":None
    }, status_code=exec.status_code, headers=exec.headers)

async def request_valid_error(req: Request, exec: RequestValidationError):
    return JSONResponse({
        "code": 500,
        "msg": "请求参数数据格式不正确:" + exec.detail,
        "data":None
    }, status_code=500, headers=exec.headers) 


def register_exception(app:FastAPI):
    # 自定义异常
    app.add_exception_handler(HTTPException, http_exception_handler)
    # 数据校验异常
    app.add_exception_handler(RequestValidationError, request_valid_error)